import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';

import { RuleListService } from './list.service';

import { Util } from '../../../common/util';

import { environment } from '../../../../environments/environment';

import { LogComponent } from "../log/log.component";

import { RuleEditComponent } from "../edit/edit.component";
import * as moment from 'moment';
import * as _ from 'lodash'
@Component({
	selector: 'rule-list',
	templateUrl: './list.component.html',
	styleUrls: ['./list.component.scss'],
	providers: [RuleListService]
})

export class RuleListComponent implements OnInit {

	@ViewChild(LogComponent) logComponent: LogComponent;
	@ViewChild(RuleEditComponent) ruleEditComponent: RuleEditComponent;
	public listData: any = {};

	public pageIndex = 1;

	public pageSize: any = environment.pageSize;

	public pages: any = [];

	public name: any = '';

	public id: any;

	public selectedRule: any = {};


	@Input()
	refresh: any = '';

	constructor(
		private ruleListService: RuleListService,
		private util: Util
	) { }

	ngOnInit() {
		this.loadList(this.pageIndex);


		// window['$'](function () {
		// 	'use strict';
		// 	// Change this to the location of your server-side upload handler:
		// 	var url = window.location.hostname === 'blueimp.github.io' ?
		// 		'//jquery-file-upload.appspot.com/' : 'server/php/';
		// 	window['$']('#fileupload').fileupload({
		// 		url: url,
		// 		dataType: 'json',
		// 		done: function (e: any, data: any) {
		// 			window['$'].each(data.result.files, function (index, file) {
		// 				window['$']('<p/>').text(file.name).appendTo('#files');
		// 			});
		// 		},

		// 	}).prop('disabled', !window['$'].support.fileInput)
		// 		.parent().addClass(window['$'].support.fileInput ? undefined : 'disabled');
		// });
	}
	// 删除规则
	delRule(item) {
		let that = this;
		// console.log(item.id);
		window['swal']({
			title: "确定?",
			text: "请确认是否要删除：" + item.name + " 指令",
			type: "warning",
			showCancelButton: true,
			confirmButtonColor: "#c9302c",
			confirmButtonText: "确定删除",
			cancelButtonText: "取消",
			// closeOnConfirm: true,
			// html: false
		}, function () {
			that.ruleListService.delRule(item).subscribe(data => {
				if (data) {
					that.loadList();
				}
			});
		});
	}
	editRule(item) {
		//  window['$']("#code").setValue("");
		if (!item) {
			item = {};
			item.type = 'auto'; 	//类型
			item.isActive = true; //是否启用
			item.attempts = 1	//重试次数
			item.orderType = 'JavaScript';	//脚本语言
			item.cron = '* * * * * *';	//默认规则
			item.ttl = 10	//超时
			// console.log(item);

		}
		window['$']('#cron').attr('placeholder',item.cron);
		this.selectedRule = _.clone(item);
		//this.ruleEditComponent.changeTab();
		window['$'](".rule-edit-modal").modal('show');
		// editor.setValue(this.selectedRule.Order);

	}


	execRule(item) {
		let that = this;
		window['swal']({
			title: "确定?",
			text: "请确认是否要执行：" + item.name + " 指令",
			type: "warning",
			showCancelButton: true,
			// confirmButtonColor: "#DD6B55",
			confirmButtonText: "确定执行",
			cancelButtonText: "取消",
			// closeOnConfirm: true,
			// html: false
		}, function () {
			that.ruleListService.execRule(item).subscribe(data => {
				if (data) {
					window['swal']("执行成功！", "", "success");
					that.loadList();
				}
			});
		});
	}

	stopRule(item) {
		let that = this;
		let postBody: any = {
			condictions: {
				"id": item.id
			},
			values: {
				"isActive": false
			}
		}
		window['swal']({
			title: "确定？",
			text: "请确认是否要停止：" + item.name + " 指令",
			type: "warning",
			showCancelButton: true,
			// confirmButtonColor: "#DD6B55",
			confirmButtonText: "确定",
			cancelButtonText: "取消",
		}, function () {
			that.ruleListService.editRule(postBody).subscribe(data => {
				if (data) {
					window['swal']("执行成功！", "", "success");
					that.loadList();
				}
			})
		})
	}

	// 显示日志modal
	showLog(item) {
		// id = 5;
		console.log(item.id);
		this.logComponent.showLog(item);
		window['$'](".rule-log-modal").modal('show');
	}
	/**
	 * [loadList 加载列表]
	 * @param {[type]} index [description]
	 */
	loadList(index?) {
		let condictions: any = {};
		if (this.name) {
			condictions.name = {
				"$like": "%" + this.name + "%"
			};
		}
		this.ruleListService.list({
			pageIndex: index ? index : this.pageIndex,
			pageSize: parseInt(this.pageSize),
			condictions: condictions
		}).subscribe(data => {
			if (data) {
				this.listData = data;
				//console.info(data);
				this.pageIndex = this.listData.pageIndex;
				this.pages = this.util.setPage(this.listData.pageSize, this.listData.total, this.pageIndex);
			}
		});
	}

	/**
	 * [function 换页]
	 * @param {[type]} type  [description]
	 * @param {[type]} index [description]
	 */
	changePage = function (type, index) {
		var pageCount = Math.ceil(this.listData.total / this.listData.pageSize);
		if (type === 'pre') {
			if (this.pageIndex - 1 > 0) {
				this.pageIndex = this.pageIndex - 1;
				this.loadList(this.pageIndex);
			}
		} else if (type === 'next') {
			if ((this.pageIndex + 1) <= pageCount) {
				this.pageIndex = this.pageIndex + 1;
				this.loadList(this.pageIndex);
			}
		} else {
			this.pageIndex = index;
			this.loadList(this.pageIndex);
		}

	}

}
